import axios from 'axios'
import { Message} from "element-ui";
import router from '../router'

axios.interceptors.response.use(success => {
    /*
     success.status为http响应 success.data为前端json响应
    * */
    if (success.status && success.status === 200 && success.data === 500) {
        Message.error({message: success.data.msg}) //success.data.msg后端定义的错误信息
        return; //错误返回空
    }
    //成功的提示
    if (success.data.msg) {
        Message.success({message: success.data.msg})
    }
    //如果没有问题
    return success.data;
}, error => {
    if (error.response.status === 504 || error.response.status === 404) {
        Message.error({message: '服务器被吃了( ╯□╰ )'})
    } else if (error.response.status === 403) {
        Message.error({message: '权限不足，请联系管理员'})
    }else if (error.response.status === 401) {
        Message.error({message: '尚未登录, 请登录!'})
        router.replace('/login') //回到登录页 需要在后端设置状态码 解决服务器启动 而前端不启动 页面报错 ‘请求失败，请联系管理员’
    } else {
        if (error.response.data.msg) {
            Message.error({message: error.response.data.msg})
        } else {
            Message.error({message: '未知错误!'})
        }
    }
    return;
})


let base = ''
//登录的时候默认支持k,v
export const postKeyValueRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`, //不是单引号 这哩是变量
        data: params,
        transformRequest: [function (data) {
            let ret = ''
            for (let i in data) {
                /*encodeURIComponent(i)是key encodeURIComponent(data[i])是value*/
                ret+=encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            }
            console.log(ret)
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}

//请求方法的封装
export const postRequest = (url, params) => {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params
    })
}

export const putRequest = (url, params) => {
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params
    })
}

export const getRequest = (url, params) => {
    return axios({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
}

export const deleteRequest = (url, params) => {
    return axios({
        method: 'delete',
        url: `${base}${url}`,
        data: params
    })
}
